<template>
  <v-card class="border" rounded="lg" variant="flat">
    <v-card-title class="d-flex align-center">
      <span class="text-h5">用户管理</span>
      <v-spacer />
      <v-text-field
        v-model="search"
        append-inner-icon="mdi-magnify"
        class="mr-2"
        density="compact"
        hide-details
        label="搜索"
        single-line
        variant="outlined"
      />
      <v-btn color="primary" prepend-icon="mdi-account-plus" variant="flat" @click="addUser">
        新增用户
      </v-btn>
    </v-card-title>
    <v-card-text>
      <v-data-table
        class="border rounded-lg"
        :headers="headers"
        :items="users"
        :items-per-page="10"
        :search="search"
      >
        <template #item.avatar="{ item }">
          <v-avatar class="my-1" size="36">
            <v-img :alt="item.name" :src="item.avatar" />
          </v-avatar>
        </template>
        <template #item.status="{ item }">
          <v-chip :color="getStatusColor(item.status)" size="small">
            {{ getStatusLabel(item.status) }}
          </v-chip>
        </template>
        <template #item.actions="{ item }">
          <v-btn
            icon
            size="small"
            variant="flat"
            @click="editUser(item)"
          >
            <v-icon>mdi-pencil</v-icon>
          </v-btn>
          <v-btn
            icon
            size="small"
            variant="flat"
            @click="deleteUser(item)"
          >
            <v-icon>mdi-delete</v-icon>
          </v-btn>
        </template>
      </v-data-table>
    </v-card-text>
  </v-card>

  <!-- 新增/编辑弹窗 -->
  <v-dialog v-model="dialog" max-width="500">
    <v-card class="border" variant="flat">
      <v-card-title>{{ dialogMode === 'add' ? '新增用户' : '编辑用户' }}</v-card-title>
      <v-card-text>
        <v-text-field v-model="dialogUser.name" label="姓名" required />
        <v-text-field v-model="dialogUser.email" label="邮箱" required />
        <v-text-field v-model="dialogUser.role" label="角色" required />
        <v-select
          v-model.number="dialogUser.status"
          item-title="label"
          item-value="value"
          :items="statusOptions"
          label="状态"
          required
        />
        <v-text-field v-model="dialogUser.lastActive" label="最后活跃时间" />
        <v-text-field v-model="dialogUser.avatar" label="头像URL" />
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn text @click="dialog = false">取消</v-btn>
        <v-btn color="primary" @click="saveUser">保存</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>

  <!-- 删除确认弹窗 -->
  <ConfirmDialog
    v-model="deleteDialog"
    :content="deleteDialogContent"
    :title="'确认删除'"
    @confirm="doDeleteUser"
  />
</template>

<script setup lang="ts">
// ================= 用户管理页面 =================
// 类型导入
  import type { Doc } from '~/convex/_generated/dataModel'
  // Convex API
  import { useConvexMutation, useConvexQuery } from '@convex-vue/core'
  // Vue 相关
  import { computed, reactive, ref } from 'vue'
  import { VBtn, VCard, VCardActions, VCardText, VCardTitle, VDialog, VSpacer, VTextField } from 'vuetify/components'
  // UI 组件
  import ConfirmDialog from '@/components/ConfirmDialog.vue'
  import { api } from '~/convex/_generated/api'

  /**
   * 搜索关键字
   */
  const search = ref('')

  /**
   * 表头配置
   */
  const headers = [
    { title: '', key: 'avatar', sortable: false, width: '60px' },
    { title: '姓名', key: 'name' },
    { title: '邮箱', key: 'email' },
    { title: '角色', key: 'role' },
    { title: '状态', key: 'status' },
    { title: '最后活跃时间', key: 'lastActive' },
    {
      title: '操作',
      key: 'actions',
      sortable: false,
      align: 'end' as const,
    },
  ] as const

  type User = Doc<'users'>

  /**
   * 用户列表，自动从 Convex 查询
   */
  const { data: users } = useConvexQuery(api.users.listUsers, {})

  // 状态选项配置
  const statusOptions = [
    { label: '激活', value: 1 },
    { label: '禁用', value: 2 },
    { label: '待审核', value: 3 },
  ]

  // 获取状态颜色（数字判断）
  function getStatusColor (status: number) {
    switch (status) {
      case 1: {
        return 'success'
      }
      case 2: {
        return 'error'
      }
      case 3: {
        return 'warning'
      }
      default: {
        return 'grey'
      }
    }
  }

  // 获取状态中文
  function getStatusLabel (status: number) {
    const found = statusOptions.find(opt => opt.value === status)
    return found ? found.label : '未知'
  }

  // ========== 弹窗相关 ========== //
  /**
   * 控制新增/编辑弹窗显示
   */
  const dialog = ref(false)
  /**
   * 弹窗模式（新增/编辑）
   */
  const dialogMode = ref<'add' | 'edit'>('add')
  /**
   * 当前弹窗用户对象
   */
  const dialogUser = reactive<Partial<User>>({})

  /**
   * 打开新增用户弹窗
   */
  function openAddDialog () {
    dialogMode.value = 'add'
    Object.assign(dialogUser, { name: '', email: '', role: '', status: 1, lastActive: '', avatar: '' })
    dialog.value = true
  }

  /**
   * 打开编辑用户弹窗
   * @param user 选中的用户
   */
  function openEditDialog (user: User) {
    dialogMode.value = 'edit'
    Object.assign(dialogUser, { ...user, status: Number(user.status) })
    dialog.value = true
  }

  // ========== Convex 增删改查 ========== //
  /**
   * 新增用户 mutation
   */
  const createUser = useConvexMutation(api.users.createUser)
  /**
   * 编辑用户 mutation
   */
  const updateUser = useConvexMutation(api.users.updateUser)
  /**
   * 删除用户 mutation
   */
  const deleteUserMutation = useConvexMutation(api.users.deleteUser)

  /**
   * 保存用户（新增或编辑）
   */
  async function saveUser () {
    if (dialogMode.value === 'add') {
      await createUser.mutate({
        name: dialogUser.name!,
        email: dialogUser.email!,
        role: dialogUser.role!,
        status: Number(dialogUser.status),
        lastActive: dialogUser.lastActive!,
        avatar: dialogUser.avatar!,
      })
    } else if (dialogMode.value === 'edit' && dialogUser._id) {
      await updateUser.mutate({
        id: dialogUser._id,
        name: dialogUser.name!,
        email: dialogUser.email!,
        role: dialogUser.role!,
        status: Number(dialogUser.status),
        lastActive: dialogUser.lastActive!,
        avatar: dialogUser.avatar!,
      })
    }
    dialog.value = false
  }

  // ========== 删除确认相关 ========== //
  /**
   * 控制删除确认弹窗显示
   */
  const deleteDialog = ref(false)
  /**
   * 待删除用户对象
   */
  const userToDelete = ref<User | null>(null)
  /**
   * 删除确认弹窗内容
   */
  const deleteDialogContent = computed(() =>
    '确定要删除用户 "' + (userToDelete.value && userToDelete.value.name ? userToDelete.value.name : '') + '" 吗？',
  )
  /**
   * 打开删除确认弹窗
   * @param user 选中的用户
   */
  function confirmDeleteUser (user: User) {
    userToDelete.value = user
    deleteDialog.value = true
  }
  /**
   * 确认删除用户
   */
  async function doDeleteUser () {
    if (userToDelete.value) {
      await deleteUserMutation.mutate({ id: userToDelete.value._id })
    }
    deleteDialog.value = false
    userToDelete.value = null
  }

  // ========== 事件绑定 ========== //
  /**
   * 新增按钮事件
   */
  function addUser () {
    openAddDialog()
  }
  /**
   * 编辑按钮事件
   * @param user 选中的用户
   */
  function editUser (user: User) {
    openEditDialog(user)
  }
  /**
   * 删除按钮事件
   * @param user 选中的用户
   */
  function deleteUser (user: User) {
    confirmDeleteUser(user)
  }
</script>
